package com.media.publish;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;
import android.view.ViewTreeObserver;
import android.view.WindowManager;

import com.baselibrary.activity.BaseActivity;
import com.baselibrary.manager.LoadingManager;
import com.baselibrary.utils.ToastUtils;
import com.media.R;
import com.media.databinding.ActivityCoverSelectBinding;
import com.media.publish.utils.LoadFrameTask;
import com.okhttp.callbacks.StringCallback;
import com.okhttp.utils.APIUrls;
import com.okhttp.utils.OkHttpUtils;
import com.qiniu.pili.droid.shortvideo.PLMediaFile;
import com.qiniu.pili.droid.shortvideo.PLShortVideoEditor;
import com.qiniu.pili.droid.shortvideo.PLVideoEditSetting;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Request;
import com.media.publish.utils.Config;
import com.media.publish.utils.VideoCoversListView;

public class CoverSelectActivity extends BaseActivity implements VideoCoversListView.OnVideoCoverChangedListener {

    private ActivityCoverSelectBinding mBinding;
    private static final int FRAME_COUNT = 10;
    private PLMediaFile mMediaFile;
    private String mSDCardVideoPath;
    private PLShortVideoEditor mShortVideoEditor;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_cover_select;
    }

    @Override
    protected void init() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        mBinding = getDataBinding();
        mSDCardVideoPath = getIntent().getStringExtra("videoPath");
        mMediaFile = new PLMediaFile(mSDCardVideoPath);
        mBinding.videoCoversView.setOnVideoRangeChangedListener(this);
        mBinding.videoCoversView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mBinding.videoCoversView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                final int sliceEdge = mBinding.videoCoversView.getWidth() / FRAME_COUNT;

                LoadFrameTask mLoadFrameTask = new LoadFrameTask(CoverSelectActivity.this, mMediaFile, FRAME_COUNT, sliceEdge, sliceEdge, new LoadFrameTask.OnLoadFrameListener() {
                    @Override
                    public void onFrameReady(Bitmap bitmap) {
                        if (bitmap != null) {
                            mBinding.videoCoversView.addBitmap(bitmap);
                        }
                    }
                });
                mLoadFrameTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }
        });
        mBinding.videoCoversView.init(this, mSDCardVideoPath, mMediaFile, FRAME_COUNT);
        initVideoData();
        initListener();
    }

    private void initListener() {
        mBinding.ivCoversBack.setOnClickListener(view -> finish());
        mBinding.tvCoversConfirm.setOnClickListener(view -> {
            Bitmap mCoversBitmap = mBinding.videoCoversView.getCoversBitmap();
            mBinding.videoCoversView.post(() -> {
                if (mCoversBitmap != null) {
                    String root = Environment.getExternalStorageDirectory().getAbsolutePath();
                    String dirName = "hanKe";
                    File appDir = new File(root, dirName);
                    if (!appDir.exists()) {
                        appDir.mkdirs();
                    }
                    String fileName = System.currentTimeMillis() + ".jpg";

                    //获取文件
                    File file = new File(appDir, fileName);
                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(file);
                        mCoversBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        String mSDCoversPath = file.getAbsolutePath();
                        fos.flush();
                        //发送广播通知系统图库刷新数据
                        //Uri uri = Uri.fromFile(file);
                        //sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                        uploadFile(mSDCoversPath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (fos != null) {
                                fos.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    ToastUtils.showShort(getApplicationContext(), "当前封面加载缓慢，正在获取封面.....");
                }
            });
        });
    }

    public void initVideoData() {
        mMediaFile = new PLMediaFile(mSDCardVideoPath);
        PLVideoEditSetting setting = new PLVideoEditSetting();
        setting.setSourceFilepath(mSDCardVideoPath);
        setting.setDestFilepath(Config.EDITED_FILE_PATH);
        setting.setGifPreviewEnabled(false);
        mShortVideoEditor = new PLShortVideoEditor(mBinding.gfCoversPreview);
        mShortVideoEditor.setVideoEditSetting(setting);
        mShortVideoEditor.getDurationMs();
        mBinding.gfCoversPreview.post(() -> {
            mShortVideoEditor.seekTo(0);
            mShortVideoEditor.pausePlayback();
        });
    }

    public void uploadFile(String coverPath) {
        if (TextUtils.isEmpty(coverPath)) {
            ToastUtils.showShort(this,"封面获取失败");
            return;
        }
        String filename = coverPath.substring(coverPath.lastIndexOf("/") + 1);
        OkHttpUtils.post()
                .addFile("file", filename, new File(coverPath))
                .url(APIUrls.URL_UPLOAD_FILES)
                .build()
                .execute(new StringCallback() {

                    @Override
                    public void onBefore(Request request, int id) {
                        LoadingManager.showLoadingDialog(CoverSelectActivity.this);
                    }

                    @Override
                    public void onAfter(int id) {
                        LoadingManager.hideLoadingDialog(CoverSelectActivity.this);
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        LoadingManager.hideLoadingDialog(CoverSelectActivity.this);
                        ToastUtils.showShort(CoverSelectActivity.this,"封面获取失败");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject object = new JSONObject(response);
                            String coverUrl = object.getString("ok");
                            File mCoversFile = new File(coverPath);
                            if (mCoversFile.exists()) {
                                mCoversFile.delete();
                            }
                            Intent intent = new Intent();
                            intent.putExtra("coversSelectUrl", coverUrl);
                            setResult(ReleaseDynamicViewModel.RESULT_COVERS, intent);
                            finish();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                    }
                });
    }

    @Override
    public void onVideoCoverChanged(long times) {
        mBinding.gfCoversPreview.post(() -> {
            mShortVideoEditor.seekTo((int) (times) / 1000);
            mShortVideoEditor.pausePlayback();
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mShortVideoEditor != null) {
            mShortVideoEditor.stopPlayback();
        }
        mBinding.videoCoversView.onDestroy();
    }


}
